<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="js,jq,小demo,H5小游戏," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="前言推箱子小游戏大家肯定都玩过，之所以写这篇文章，是觉得这个小游戏足够简单好理解，大家看完文章之后，自己也能花上半天功夫敲出一个推箱子小游戏来，如果喜欢的话可以点波赞，或者关注一下，希望本文可以帮到大家。  本文首发于我的个人blog：obkoro1.com  demo：推箱子小游戏步骤解析：本文代码已经放在了github上面了,里面也进行了很详细的代码注释，可以copy下来，在本地运行一下看看。">
<meta name="keywords" content="js,jq,小demo,H5小游戏">
<meta property="og:type" content="article">
<meta property="og:title" content="js 简单的推箱子小游戏步骤解析--大家都玩过的">
<meta property="og:url" content="http://yoursite.com/2018/01/07/js-简单的推箱子小游戏步骤解析-大家都玩过的/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="前言推箱子小游戏大家肯定都玩过，之所以写这篇文章，是觉得这个小游戏足够简单好理解，大家看完文章之后，自己也能花上半天功夫敲出一个推箱子小游戏来，如果喜欢的话可以点波赞，或者关注一下，希望本文可以帮到大家。  本文首发于我的个人blog：obkoro1.com  demo：推箱子小游戏步骤解析：本文代码已经放在了github上面了,里面也进行了很详细的代码注释，可以copy下来，在本地运行一下看看。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/160d1149856a3714?w=503&h=727&f=png&s=48024?raw=true">
<meta property="og:updated_time" content="2019-06-15T06:19:47.628Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="js 简单的推箱子小游戏步骤解析--大家都玩过的">
<meta name="twitter:description" content="前言推箱子小游戏大家肯定都玩过，之所以写这篇文章，是觉得这个小游戏足够简单好理解，大家看完文章之后，自己也能花上半天功夫敲出一个推箱子小游戏来，如果喜欢的话可以点波赞，或者关注一下，希望本文可以帮到大家。  本文首发于我的个人blog：obkoro1.com  demo：推箱子小游戏步骤解析：本文代码已经放在了github上面了,里面也进行了很详细的代码注释，可以copy下来，在本地运行一下看看。">
<meta name="twitter:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/160d1149856a3714?w=503&h=727&f=png&s=48024?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/01/07/js-简单的推箱子小游戏步骤解析-大家都玩过的/"/>





  <title>js 简单的推箱子小游戏步骤解析--大家都玩过的 | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/01/07/js-简单的推箱子小游戏步骤解析-大家都玩过的/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">js 简单的推箱子小游戏步骤解析--大家都玩过的</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-07T23:45:15+08:00">
                2018-01-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/小demo/" itemprop="url" rel="index">
                    <span itemprop="name">小demo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/01/07/js-简单的推箱子小游戏步骤解析-大家都玩过的/" class="leancloud_visitors" data-flag-title="js 简单的推箱子小游戏步骤解析--大家都玩过的">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,288 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>推箱子小游戏大家肯定都玩过，之所以写这篇文章，是觉得这个小游戏足够简单好理解，大家看完文章之后，自己也能花上半天功夫敲出一个推箱子小游戏来，如果喜欢的话可以点波赞，或者关注一下，希望本文可以帮到大家。</p>
<blockquote>
<p>本文首发于我的个人blog：<a href="http://obkoro1.com/" target="_blank" rel="noopener">obkoro1.com</a></p>
</blockquote>
<h3 id="demo：推箱子小游戏"><a href="#demo：推箱子小游戏" class="headerlink" title="demo：推箱子小游戏"></a>demo：<a href="http://obkoro1.com/web_accumulate/example/pushKoro/index.html" target="_blank" rel="noopener">推箱子小游戏</a></h3><h2 id="步骤解析："><a href="#步骤解析：" class="headerlink" title="步骤解析："></a>步骤解析：</h2><p><strong>本文代码已经放在了<a href="https://github.com/OBKoro1/web_accumulate/blob/d6b599ca22d8656d3f31f80bffa976fac36d2d75/example/pushKoro/index.html" target="_blank" rel="noopener">github</a>上面了,里面也进行了很详细的代码注释，可以copy下来，在本地运行一下看看</strong>。</p>
<h3 id="1-渲染地图"><a href="#1-渲染地图" class="headerlink" title="1. 渲染地图"></a>1. 渲染地图</h3><ol>
<li><p>html结构：<br><img src="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/160d1149856a3714?w=503&amp;h=727&amp;f=png&amp;s=48024?raw=true" alt=""></p>
<pre><code>html结构十分简单，只要弄一堆div，来放置地图的class就可以了，我这里初始化了12*9个div，地图里最多九行高度。   
这些div都是同样大小，地图渲染出来区别的只是颜色的不同。
</code></pre><ol start="2">
<li><p>地图函数：</p>
<p>  var box=$(‘.box div’); //地图使用的div集合<br>  function create(){ //创建地图函数<br>  box.each(function(index){ //index的数量是固定的，是box div下面div的数量</p>
<pre><code> // 每次创建地图初始化div
box.eq(index).removeClass();
</code></pre><p>  });<br>  box.each(function(index,element){ //循环整个div的数量 二维数组里数量不够的 默认为空白<br>  //level为关卡数 根据关卡渲染地图 builder为二维数组，为地图关卡</p>
<pre><code>if(builder[level][index]){ //过滤0
    box.eq(index).addClass(&apos;type&apos;+builder[level][index]);
}
</code></pre><p>  });<br>  box.eq(origin[level]).addClass(“pusher”); //推箱人 皮卡丘位置<br>  }</p>
<p>  //第一关的地图长这样（下面只是栗子，不是代码），0代表不可抵达区域，1代表目标（要被推到的地方），<br>  //2代表普通路径（可以走的），3代表墙，4代表箱子<br>  [0,0,0,0,3,3,3,0,0,0,0,0,<br>  0,0,0,0,3,1,3,0,0,0,0,0,<br>  0,0,0,0,3,2,3,3,3,3,0,0,<br>  0,0,3,3,3,4,2,4,1,3,0,0,<br>  0,0,3,1,2,4,2,3,3,3,0,0,<br>  0,0,3,3,3,3,4,3,0,0,0,0,<br>  0,0,0,0,0,3,1,3,0,0,0,0,<br>  0,0,0,0,0,3,3,3,0,0,0,0] </p>
</li>
</ol>
</li>
</ol>
<h3 id="2-捕获键盘事件-判断是否可以移动"><a href="#2-捕获键盘事件-判断是否可以移动" class="headerlink" title="2. 捕获键盘事件,判断是否可以移动"></a>2. 捕获键盘事件,判断是否可以移动</h3><p>使用<a href="http://www.w3school.com.cn/jquery/event_keydown.asp" target="_blank" rel="noopener">$(document).keydown()</a>jqery事件，捕获键盘事件。</p>
<ol>
<li><p>捕获键盘事件，上下左右以及wsad。 </p>
<pre><code>$(document).keydown(function (e) {
 var key=e.which;
 switch(key){
 //col 的值为12，上下移动要12个div为一个周期
 //方向键上或者w
 case 87:
 case 38:
     move(-col);//判断移动函数
 break;
 //方向键下或者s
 case 83:
 case 40:
    move(col);
 break;
 //方向键左或者a
 case 65:
 case 37:
     move(-1);
 break;
 //方向键右或者d
 case 68:
 case 39:
     move(1);
 break;
 }
setTimeout(win,500); //按键之后调判断是否过关
});
</code></pre></li>
<li><p>判断是否可以移动。</p>
</li>
</ol>
<p>分为两个判断条件：一个是推箱子，一个是不推箱子 自然移动，否则不移动皮卡丘。</p>
<pre><code>function move(step){ //是否移动判断
     // 分为两个判断条件一个是推箱子，一个是不推箱子 自然移动。 否则不移动皮卡丘
     //step 上下是12个div一个周期，左右是1个div positin是皮卡丘的原来位置
    var pikaqiu1=box.eq(position);//皮卡丘现在的地方
    var pikaqiu2=box.eq(position+step);//皮卡丘要去的下一个地方
    var pushBox=box.eq(position+step*2);//箱子要去的下一个地方
    if(!pikaqiu2.hasClass(&apos;type4&apos;)&amp;&amp;( pikaqiu2.hasClass(&apos;type1&apos;)||pikaqiu2.hasClass(&apos;type2&apos;))){ //自然移动
        //判断：如果下一个div的class不包含type4(箱子)，并且 下一个div含有type1(目标位置)，或者type2(普通路径)
        //这一步和下一步判断是否有type4的原因是普通路径会变成有type4的路径，这时候就会出现问题
        pikaqiu1.removeClass(&quot;pusher&quot;); //移除当前皮卡丘
        pikaqiu2.addClass(&quot;pusher&quot;);//移动皮卡丘到下一个位置
        position=position+step;//增加position值
    }
    else if((pikaqiu2.hasClass(&apos;type4&apos;))&amp;&amp;(!pushBox.hasClass(&apos;type4&apos;))&amp;&amp;(pushBox.hasClass(&apos;type1&apos;)|| pushBox.hasClass(&apos;type2&apos;)) ) {
        //推箱子    
        //如果下一个div的class包含type4(箱子)并且 不包含重叠type4(箱子) 并且 包含class type1（目标位置）或者 包含type2(空路)
       pikaqiu2.removeClass(&apos;type4&apos;);//移除当前箱子
        pikaqiu1.removeClass(&quot;pusher&quot;);//移除当前皮卡丘
        pushBox.addClass(&apos;type4&apos;);//移动箱子到下一个位置
        pikaqiu2.addClass(&quot;pusher&quot;).addClass(&quot;type2&quot;);//
        //本来是type4 移除之后，这里没有class了，要变成普通路径
        position=position+step;//增加position值 
    }
}    
</code></pre><h3 id="3-胜利判断："><a href="#3-胜利判断：" class="headerlink" title="3.胜利判断："></a>3.胜利判断：</h3><p>每次移动都要调用这个胜利判断。</p>
<pre><code>function win(){ //胜利条件判断
    if($(&quot;.type1.type4&quot;).length===goal){ //推的箱子与关卡设置通过箱子的数量对比
        if(level&lt;9) {
            alert(&quot;666，挑战下一关吧--OBKoro1&quot;);
            level++; //关卡+1
            goal = goalList[level];
            position = origin[level];
            create();
        }else {
            alert(&quot;厉害啊 大佬 通关了都&quot;);
        }
    }
}
</code></pre><h3 id="代码地址、demo地址"><a href="#代码地址、demo地址" class="headerlink" title="代码地址、demo地址"></a><a href="https://github.com/OBKoro1/web_accumulate/blob/d6b599ca22d8656d3f31f80bffa976fac36d2d75/example/pushKoro/index.html" target="_blank" rel="noopener">代码地址</a>、<a href="http://obkoro1.com/web_accumulate/example/pushKoro/index.html" target="_blank" rel="noopener">demo地址</a></h3><h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>本文到这里就结束了，喜欢的话，赶紧自己去敲一个出来，希望本文可以帮助大家发散思维。</p>
<p><strong>最后</strong>：如需转载，请放上原文链接并署名。码字不易，<strong>感谢</strong>支持！本人写文章本着交流记录的心态，写的不好之处，不撕逼，但是欢迎指点。然后就是希望看完的朋友点个<strong>喜欢</strong>，也可以<strong>关注</strong>一下我。<br><strong><a href="http://obkoro1.com/" target="_blank" rel="noopener">个人blog</a></strong> and <strong><a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" rel="noopener">掘金个人主页</a></strong>  </p>
<p>以上2018.1.7</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          
            <a href="/tags/jq/" rel="tag"><i class="fa fa-tag"></i> jq</a>
          
            <a href="/tags/小demo/" rel="tag"><i class="fa fa-tag"></i> 小demo</a>
          
            <a href="/tags/H5小游戏/" rel="tag"><i class="fa fa-tag"></i> H5小游戏</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/12/25/vue先hash-模式部署项目，然后开启histroy模式-，引发的几个问题以及histroy模式的开启方式、优点/" rel="next" title="vue先hash 模式部署项目，然后开启histroy模式 ，引发的几个问题以及histroy模式的开启方式、优点">
                <i class="fa fa-chevron-left"></i> vue先hash 模式部署项目，然后开启histroy模式 ，引发的几个问题以及histroy模式的开启方式、优点
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/09/【读书笔记】《高性能JavaScript》/" rel="prev" title="【读书笔记】《高性能JavaScript》">
                【读书笔记】《高性能JavaScript》 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#demo：推箱子小游戏"><span class="nav-number">1.1.</span> <span class="nav-text">demo：推箱子小游戏</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤解析："><span class="nav-number">2.</span> <span class="nav-text">步骤解析：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-渲染地图"><span class="nav-number">2.1.</span> <span class="nav-text">1. 渲染地图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-捕获键盘事件-判断是否可以移动"><span class="nav-number">2.2.</span> <span class="nav-text">2. 捕获键盘事件,判断是否可以移动</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-胜利判断："><span class="nav-number">2.3.</span> <span class="nav-text">3.胜利判断：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#代码地址、demo地址"><span class="nav-number">2.4.</span> <span class="nav-text">代码地址、demo地址</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">3.</span> <span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

